#-------------------------------------#
#   调用摄像头或者视频进行检测
#   调用摄像头直接运行即可
#   调用视频可以将cv2.VideoCapture()指定路径
#   视频的保存并不难，可以百度一下看看
#-------------------------------------#
import time
import cv2
import numpy as np
from keras.layers import Input
from PIL import Image
from yolo import YOLO

yolo = YOLO()

#-------------------------------------#
#   直接调用摄像头:capture=cv2.VideoCapture(0)
#   调用视频capture=cv2.VideoCapture('vedio/4.mp4')
#-------------------------------------#
capture=cv2.VideoCapture(0)

fps = 0.0

while(True):
    t1 = time.time()
    
    # 读取某一帧
    ret,frame=capture.read()
    # 格式转变，BGRtoRGB
    frame = cv2.cvtColor(frame,cv2.COLOR_BGR2RGB)
    # 转变成Image
    img = Image.fromarray(np.uint8(frame))
    # 进行检测，输出是带标框的图像img_detection
    img_detected, res_boxes, res_socres, res_classes = yolo.detect_image(img)
    img_detection = np.array(img_detected)
    # RGBtoBGR满足opencv显示格式
    img_show = cv2.cvtColor(img_detection,cv2.COLOR_RGB2BGR)
    
    #计算并输出fps
    fps  = ( fps + (1./(time.time()-t1)) ) / 2
    print("fps= %.2f"%(fps))

    #显示带标框的图像和fps值
    img_show = cv2.putText(img_show, "fps= %.2f"%(fps), (0, 40), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
    cv2.imshow("hand detection",img_show)

    #按q退出
    if cv2.waitKey(1) & 0xFF == ord('Q'):
        break
        
yolo.close_session()
    
